'use strict';

import React from 'react';

import {
    HttpService,
    Toast
} from '../../utils'
 import $ from 'jquery'

import phone from '../../img/login/phone.png'
import pwd from '../../img/login/pwd.png'
import user from '../../img/login/user.png'



import {
    connect
} from 'react-redux';
import {
    bindActionCreators
} from 'redux';

//import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import Link from '../common/Link'
import WxServer from '../../wx/WxServer'

import {
    doLogin2
} from '../../action/index'
import {
    urlKey
} from '../../Tool'

class Login extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.state = {
            model: {},
            // banners: {},
            flag: false,
            wxlogincbFlag: false,
            openid: '',
            wxgo: false,
            way: 0,
            timer: 119,
            text: '获取验证码',
            disabled: false
        };

    }

    componentWillMount() {
        document.title="商户中心"
        const token=localStorage.btoken;
            if(token){
                this.context.router.push('/businessIndex');
                return;
            }
        // if (/micromessenger/.test(navigator.userAgent.toLowerCase()) && location.host.indexOf('wx.17find.com') > -1) {
        //     if (urlKey('code')) {
        //         this.a();
        //     } else {
        //         let gotolink = 'http://wx.17find.com/'
        //         if (urlKey('newlink') != '')
        //             gotolink += '?newlink=pay'
        //         location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
        //             'appid=wx85577a457cfcd222&redirect_uri=' + encodeURIComponent(gotolink) + '&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect'
        //     }
        // }
    }

    componentDidMount() {
        setTimeout(() => {
            this.setState({
                wxgo: false
            })
        }, 6000)
    }

    componentWillUnmount() {
        localStorage.business = 1;

    }


    async login() {
        const phone = this.refs.phone.value;
        const pwd = this.refs.pwd.value;
        const way = this.state.way;
        if (phone == '') {
            Toast.toast('请输入手机号');
            return;
        } else if (!/^1[34578]\d{9}$/.test(phone)) {
            Toast.toast('手机格式不正确');
            return;
        }
        if (!pwd) {
            Toast.toast(`请输入${way == 0 ? '密码' : '验证码'}`);
            return;
        }


        let loginUrl ='/jf/business/companyuser/login'
        let data = {
            phone: phone,
        }

        if (way == 1) { //短信登录
            loginUrl = '/jf/business/companyuser/loginsms'
            data.code = pwd
        } else {
            data.pwd = pwd
        }
        var result = await HttpService.query({
            url: loginUrl,
            async: false,
            data
        });
        if (result.code == 50006) {
            localStorage.btoken = result.data.token;
            // debugger
            if(result.data.company){
                localStorage.companyId=result.data.company.id;
            }

            this.context.router.push('/businessIndex');
            return;
        }
        Toast.toast(result.data)
    }

    //登录方式切换
    loginWay(way) {
        this.setState({
            way
        })
        this.refs.pwd.value = '';
    }

    //发送验证码
    async sendCode() {
        let {
            timer,
            disabled
        } = this.state;
        if (disabled)
            return
        const phone = this.refs.phone.value;
        if (phone == '') {
            Toast.toast('请输入手机号');
            return;
        } else if (!/^1[34578]\d{9}$/.test(phone)) {
            Toast.toast('手机格式不正确');
            return;
        }
        // let code = await HttpService.save({
        //     url: "/app/user/checkTelephone",
        //     data: {
        //         account: phone,
        //         weixinclient: true
        //     }
        // });
        // if (code.code != 10002) {
        //     if (code.msg == '手机号可以注册')
        //         code.msg = '手机号未注册'
        //     Toast.toast(code.msg)
        //     return
        // }
        var result = await HttpService.query({
            url: '/jf/business/companyuser/generateSMSCode',
            data: {
                phone: phone,
                module: 'loginsms'
            }
        });
        if (result.code == 10004) {
            sessionStorage.sendCode = 1
            this.setState({
                disabled: true,
                text: timer + '秒后重发'
            });
            this.countdown = setInterval(() => {
                --timer;
                if (timer <= 0) {
                    this.setState({
                        disabled: false,
                        text: '获取验证码',
                        timer: 119
                    });
                    clearInterval(this.countdown);
                    return;
                }
                this.setState({
                    disabled: true,
                    text: timer + '秒后重发',
                    timer
                })
            }, 1000);
        } else {
            Toast.toast(result.msg)
        }
    }

    render() {
        const {
            model,
            flag,
            wxgo,
            way,
            text,
            disabled
        } = this.state;
        return (
            <div>
                {wxgo == true
                    ? <div className='loadwx'></div>
                    : <div>
                        {flag == false
                            ? <div className="app-login app-padding-lr24" ref='_login'>
                                <div className="step">
                                    <div className="s-center">
                                        <div className="login-img">
                                            <img src={user} className="app-wh100-all"/>
                                        </div>
                                    </div>
                                </div>
                                <div className='loginwaybar'>
                                    <label onClick={this.loginWay.bind(this, 0)} className={way == 0 ? 'active' : null}>密码登录</label>
                                    <label onClick={this.loginWay.bind(this, 1)} className={way == 1 ? 'active' : null}>验证码登录</label>
                                </div>
                                <div className="step border-bottom app-wh120 relative">
                                    <div className="app-wh-45 app-margin-right24">
                                        <img className="app-wh100-all-radius" src={phone}/>
                                    </div>
                                    <div className="s-flex1 app-666-font30">
                                        <input className="app-333-font28 login-input" maxLength='11' placeholder='手机号'
                                               type="tel" ref='phone'/>
                                    </div>
                                    {way == 1 ?
                                        <input type='button' value={text}
                                               className={disabled ? 'loginbtncode lbc_disabled' : 'loginbtncode'}
                                               onClick={this.sendCode.bind(this)}/>
                                        : null
                                    }
                                </div>
                                <div className="step border-bottom app-wh120">
                                    <div className="app-wh-45 app-margin-right24">
                                        <img className="app-wh100-all-radius" src={pwd}/>
                                    </div>
                                    <div className="s-flex1 app-666-font30">
                                        <input className="app-333-font28 login-input"
                                               placeholder={way == 0 ? '6-20位字符密码，区分大小写' : '手机验证码'} type="password"
                                               ref="pwd"/>
                                    </div>
                                </div>
                                <div className="step app-yellow-radius-check-button login-btn"
                                     onClick={this.login.bind(this)}>
                                    <div className="s-center">登录</div>
                                </div>
                                <div className="step">
                                    <Link to={'/businessReg'} className="s-flex1 app-a">
                                        <div className="s-flex1 s-j-end app-333-font28">新用户开通</div>
                                    </Link>
                                    <div className="app-padding-lr50 app-with1" style={{marginTop: '.2rem'}}></div>
                                    <Link to={'/businessForgetPwd'} className="s-flex1 app-a">
                                        <div className="s-flex1 app-333-font28">忘记密码</div>
                                    </Link>
                                </div>
                            </div>
                            : ''
                        }
                    </div>}
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {};
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        doLogin2: doLogin2
    }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(Login)
